// chat-history.js
Page({
  data: {
    chatHistory: [],
    filteredHistory: [],
    searchText: '',
    isLoading: false,
    showDetailModal: false,
    selectedChat: null,
    aiAnswers: [],
    scrollToView: ''
  },

  onLoad: function(options) {
    console.log('对话记录页面加载');
    this.loadChatHistory();
    
    // 测试删除功能
    console.log('当前聊天历史:', this.data.chatHistory);
  },

  onShow: function() {
    console.log('对话记录页面显示');
    // 每次显示时重新加载数据
    this.loadChatHistory();
  },

  // 加载对话记录
  loadChatHistory: function() {
    this.setData({
      isLoading: true
    });

    try {
      // 从本地存储获取对话记录
      const history = wx.getStorageSync('chatHistory') || [];
      
      // 按时间倒序排列
      const sortedHistory = history.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
      
      this.setData({
        chatHistory: sortedHistory,
        filteredHistory: sortedHistory,
        isLoading: false
      });
      
      console.log('加载对话记录成功:', sortedHistory.length, '条');
      console.log('对话记录详情:', sortedHistory);
      
      // 测试删除功能是否可用
      if (sortedHistory.length > 0) {
        console.log('第一个对话的ID:', sortedHistory[0].id);
        console.log('删除功能测试准备就绪');
      }
    } catch (error) {
      console.error('加载对话记录失败:', error);
      this.setData({
        isLoading: false
      });
      
      wx.showToast({
        title: '加载失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 搜索输入
  onSearchInput: function(e) {
    const searchText = e.detail.value;
    this.setData({
      searchText: searchText
    });
    
    // 实时搜索
    this.filterHistory(searchText);
  },

  // 搜索确认
  onSearch: function(e) {
    const searchText = e.detail.value;
    this.filterHistory(searchText);
  },

  // 过滤对话记录
  filterHistory: function(searchText) {
    if (!searchText.trim()) {
      this.setData({
        filteredHistory: this.data.chatHistory
      });
      return;
    }

    const filtered = this.data.chatHistory.filter(chat => {
      return chat.title.toLowerCase().includes(searchText.toLowerCase()) ||
             chat.preview.toLowerCase().includes(searchText.toLowerCase());
    });

    this.setData({
      filteredHistory: filtered
    });
  },

  // 显示对话详情
  showChatDetail: function(e) {
    const chat = e.currentTarget.dataset.chat;
    console.log('显示对话详情:', chat);
    
    // 过滤出AI的回答，排除欢迎消息和其他无关内容
    const aiAnswers = this.filterAIAnswers(chat.messages);
    
    this.setData({
      selectedChat: chat,
      aiAnswers: aiAnswers,
      showDetailModal: true
    });
    
    // 延迟滚动到底部，确保DOM渲染完成
    setTimeout(() => {
      this.scrollToBottom();
    }, 300);
  },

  // 过滤AI回答内容
  filterAIAnswers: function(messages) {
    if (!messages || !Array.isArray(messages)) {
      return [];
    }
    
    const aiMessages = messages.filter(msg => msg.type === 'ai' && msg.content);
    const answers = [];
    
    for (let i = 0; i < aiMessages.length; i++) {
      const content = aiMessages[i].content.trim();
      
      // 排除欢迎消息
      if (content.includes('你好!我是AI解题助手') || 
          content.includes('有什么学习问题可以随时问我') ||
          content.includes('欢迎') ||
          content.includes('很高兴为您服务')) {
        continue;
      }
      
      // 排除空内容或加载中状态
      if (content && !content.includes('正在思考') && !content.includes('加载中')) {
        answers.push(content);
      }
    }
    
    return answers;
  },

  // 隐藏对话详情
  hideChatDetail: function() {
    this.setData({
      showDetailModal: false,
      selectedChat: null
    });
  },

  // 继续对话
  continueChat: function() {
    const chatId = this.data.selectedChat.id;
    this.hideChatDetail();
    
    // 跳转到AI聊天页面，并传递对话ID
    wx.redirectTo({
      url: `/pages/ai-chat/ai-chat?chatId=${chatId}`
    });
  },

  // 长按显示删除选项
  showDeleteOptions: function(e) {
    console.log('长按删除选项', e);
    const chatId = e.currentTarget.dataset.id;
    const chat = this.data.chatHistory.find(item => item.id === chatId);
    
    if (!chat) {
      console.log('长按：未找到对话');
      return;
    }

    console.log('长按：显示操作菜单');
    wx.showActionSheet({
      itemList: ['删除对话', '查看详情'],
      success: (res) => {
        console.log('操作菜单选择:', res.tapIndex);
        if (res.tapIndex === 0) {
          // 删除对话
          this.confirmDeleteChat(chatId, chat.title);
        } else if (res.tapIndex === 1) {
          // 查看详情
          this.showChatDetail(e);
        }
      },
      fail: (err) => {
        console.log('操作菜单失败:', err);
      }
    });
  },

  // 确认删除对话
  confirmDeleteChat: function(chatId, chatTitle) {
    console.log('显示删除确认对话框', chatId, chatTitle);
    wx.showModal({
      title: '确认删除',
      content: `确定要删除对话"${chatTitle}"吗？`,
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: (res) => {
        console.log('删除确认结果:', res);
        if (res.confirm) {
          console.log('用户确认删除');
          this.deleteChatById(chatId);
        } else {
          console.log('用户取消删除');
        }
      },
      fail: (err) => {
        console.log('删除确认对话框失败:', err);
      }
    });
  },

  // 删除对话（点击垃圾桶图标）
  deleteChat: function(e) {
    console.log('删除按钮被点击', e);
    const chatId = e.currentTarget.dataset.id;
    console.log('要删除的对话ID:', chatId);
    
    const chat = this.data.chatHistory.find(item => item.id === chatId);
    console.log('找到的对话:', chat);
    
    if (!chat) {
      console.log('未找到对话');
      wx.showToast({
        title: '对话不存在',
        icon: 'error'
      });
      return;
    }

    this.confirmDeleteChat(chatId, chat.title);
  },

  // 根据ID删除对话
  deleteChatById: function(chatId) {
    try {
      const updatedHistory = this.data.chatHistory.filter(chat => chat.id !== chatId);
      
      // 更新本地存储
      wx.setStorageSync('chatHistory', updatedHistory);
      
      // 更新页面数据
      this.setData({
        chatHistory: updatedHistory,
        filteredHistory: updatedHistory.filter(chat => {
          if (!this.data.searchText.trim()) return true;
          return chat.title.toLowerCase().includes(this.data.searchText.toLowerCase()) ||
                 chat.preview.toLowerCase().includes(this.data.searchText.toLowerCase());
        })
      });
      
      wx.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 1500
      });
      
      console.log('删除对话成功:', chatId);
    } catch (error) {
      console.error('删除对话失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 清空所有记录
  clearAllHistory: function() {
    if (this.data.chatHistory.length === 0) {
      wx.showToast({
        title: '暂无记录可清空',
        icon: 'none',
        duration: 1500
      });
      return;
    }

    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有对话记录吗？此操作不可恢复！',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          this.clearAllChatHistory();
        }
      }
    });
  },

  // 清空所有对话记录
  clearAllChatHistory: function() {
    try {
      // 清空本地存储
      wx.removeStorageSync('chatHistory');
      
      // 更新页面数据
      this.setData({
        chatHistory: [],
        filteredHistory: [],
        searchText: ''
      });
      
      wx.showToast({
        title: '清空成功',
        icon: 'success',
        duration: 1500
      });
      
      console.log('清空所有对话记录成功');
    } catch (error) {
      console.error('清空对话记录失败:', error);
      wx.showToast({
        title: '清空失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 滚动到底部
  scrollToBottom: function() {
    if (!this.data.aiAnswers || this.data.aiAnswers.length === 0) return;
    
    const lastIndex = this.data.aiAnswers.length - 1;
    this.setData({
      scrollToView: `ai-answer-${lastIndex}`
    });
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack({
      delta: 1
    });
  }
});
